/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.aaron.platform.view;

import com.aaron.platform.dao.PageInfo;
import com.aaron.platform.entity.*;
import com.aaron.platform.exceptions.*;
import com.aaron.platform.service.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.logging.Level;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

/**
 * 车辆基本信息管理页面
 *
 * @author Administrator
 */
public class MotorBookListBean extends DataListBean {

    private static Logger logger = Logger.getLogger(MotorBookListBean.class);
    /**
     * 车牌号
     */
    private String motorNumber;
    /**
     * 区域ID
     */
    private int domainId;
    /**
     * 查询日期
     */
    private Date searchDate;
    /**
     * 驾驶员
     */
    private String driverName;
    private IMotorInfoMgr motorInfoMgr;
    private IDomainService domainMgr;
    private IUserService userService;

    private MailService mailService;
    
    private WlbMotorInfo currentMotorInfo;
    private WlbMotorBook currentMotorBook;
    private List<SelectItem> domainList;
    private DataModel motorBooks;
    /**
     * 1:view 2:edit 3:delete
     */
    private int currentOperation = 1;

    public MotorBookListBean() {
        super();
        this.tableTitle = FacesUtil.getString("content_title_motor_list");

        // 删除、编辑、查看操作
        this.deletable = true;
        this.editable = true;
        this.viewable = true;
        this.multiSelectable = false;

        // 设置分页信息
        pagable = true;
        init();

    }

    /**
     * 初始化查询条件
     */
    private void init() {
        motorNumber = "";
        driverName = "";
        domainId = 0;
        searchDate = new Date();
        currentMotorInfo = null;
        this.data = new ListDataModel();
        this.motorBooks = new ListDataModel();
        pageInfo = new PageInfo<WlbMotorInfo>();
    }

    public void reset() {
        init();
    }

    @Override
    public void queryData() {

        // 设置查询条件
        Properties properties = new Properties();
        if (this.domainId != 0) {
            properties.setProperty(WlbMotorInfo.PROPERTY_DOMAIN_ID, String.valueOf(this.domainId));
        }
        if (!StringUtils.isEmpty(this.driverName)) {
            properties.setProperty(WlbMotorInfo.PROPERTY_DRIVER_NAME, StringUtils.trim(this.driverName));
        }
        if (!StringUtils.isEmpty(this.motorNumber)) {
            properties.setProperty(WlbMotorInfo.PROPERTY_MOTOR_NUMBER, StringUtils.trim(this.motorNumber));
        }
        if (this.searchDate != null) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            properties.setProperty(WlbMotorBook.PROPERTY_BOOK_DATE_FROM, df.format(searchDate));
            properties.setProperty(WlbMotorBook.PROPERTY_BOOK_DATE_TO, df.format(searchDate));
        }

        // 查询车辆信息
        pageInfo = motorInfoMgr.findByConditionWithBooks(properties, pageInfo.getStartIndex(), pageInfo.getPageSize());
        logger.info("Query motorInfo with books list finished.");
        data.setWrappedData(pageInfo.getItems());
    }

    @Override
    public void initColumnHeaders() {
        headerColumns.add(new ColumnType(ColumnType.COLUMN_TEXT, "motor_number",
                FacesUtil.getString("table_column_motor_number"), false, "12%"));
        headerColumns.add(new ColumnType(ColumnType.COLUMN_TEXT, "motor_style",
                FacesUtil.getString("table_column_motor_style"), false, "12%"));
        headerColumns.add(new ColumnType(ColumnType.COLUMN_TEXT, "motor_domain",
                FacesUtil.getString("table_column_motor_domain"), false, "10%"));
        headerColumns.add(new ColumnType(ColumnType.COLUMN_TEXT, "driver_name",
                FacesUtil.getString("table_column_motor_drivername"), false, "10%"));
        headerColumns.add(new ColumnType(ColumnType.COLUMN_TEXT, "driver_phone",
                FacesUtil.getString("table_column_motor_driverphone"), false, "10%"));
        headerColumns.add(new ColumnType(ColumnType.COLUMN_TEXT, "book_date",
                FacesUtil.getString("table_column_motor_bookdate"), false, "10%"));
        headerColumns.add(new ColumnType(ColumnType.COLUMN_TEXT, "date_morning",
                FacesUtil.getString("table_column_motor_morning"), false, "10%"));
        headerColumns.add(new ColumnType(ColumnType.COLUMN_TEXT, "date_afternoon",
                FacesUtil.getString("table_column_motor_afternoon"), false, "10%"));
    }

    @Override
    public String getColumnValue() {
        String columnName = getColumnName();
        increaseColumnIndex();

        WlbMotorInfo obj = (WlbMotorInfo) data.getRowData();
        if (columnName.equals("motor_number")) {
            return obj.getMotorNum();
        } else if (columnName.equals("motor_style")) {
            return obj.getMotorStyle();
        } else if (columnName.equals("motor_domain")) {
            return obj.getDomainInfo().getDomainName();
        } else if (columnName.equals("driver_name")) {
            return obj.getDriverName();
        } else if (columnName.equals("driver_phone")) {
            return obj.getDriverPhone();
        } else if (columnName.equals("book_date")) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            return df.format(searchDate);
        } else if (columnName.equals("date_morning")) {
            if (obj.isMorningBooked()) {
                return FacesUtil.getString("table_column_motor_booked");
            } else {
                return "";
            }
        } else if (columnName.equals("date_afternoon")) {
            if (obj.isAfternoonBooked()) {
                return FacesUtil.getString("table_column_motor_booked");
            } else {
                return "";
            }
        } else {
            return null;
        }
    }

    @Override
    public String editData() {
        currentMotorInfo = (WlbMotorInfo) data.getRowData();
        currentOperation = 2;
        return "motorinfo_input";
    }

    @Override
    public String showDetail() {
        currentMotorInfo = (WlbMotorInfo) data.getRowData();
        currentMotorBook = new WlbMotorBook();
        currentMotorBook.setWlbMotorInfo(currentMotorInfo);
        currentMotorBook.setBookDate(searchDate);
        if (currentMotorInfo.getWlbMotorBooks() != null && currentMotorInfo.getWlbMotorBooks().size() > 0) {
            motorBooks.setWrappedData(currentMotorInfo.getWlbMotorBooks());
        } else {
            motorBooks = new ListDataModel();
        }
        currentOperation = 1;
        return "motorbook_add";
    }

    public String bookMotor() {

        // 判断日期：>=当前日期
        Date nowDate = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String nowDateStr = df.format(nowDate);
        String searchDateStr = df.format(searchDate);
        if (!StringUtils.equalsIgnoreCase(nowDateStr, searchDateStr) && searchDate.before(nowDate)) {
            FacesUtil.addErrorMessage(null, "er_motorbook_book_yestoday_not_allowed");
            return null;
        }

        currentMotorInfo = (WlbMotorInfo) data.getRowData();
        currentMotorBook = new WlbMotorBook();
        currentMotorBook.setWlbMotorInfo(currentMotorInfo);
        currentMotorBook.setBookDate(searchDate);

        // 获取预约人信息
        UserSession userSession = null;
        HttpSession httpSession;
        try {
            httpSession = FacesUtil.getClientSession();
            userSession = (UserSession) httpSession.getAttribute("user");
        } catch (UserSessionException ex) {
            java.util.logging.Logger.getLogger(MotorBookListBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        currentMotorBook.setBooker(userSession.getUserInfo().getUserChName());

        if (currentMotorInfo.getWlbMotorBooks() != null && currentMotorInfo.getWlbMotorBooks().size() > 0) {
            motorBooks.setWrappedData(currentMotorInfo.getWlbMotorBooks());
        } else {
            motorBooks = new ListDataModel();
        }
        currentOperation = 2;
        return "motorbook_add";
    }

    public String addBook() {

        // 判断输入条件
        if (currentMotorBook.getBookStyle() == 0) {
            FacesUtil.addErrorMessage(null, "er_motorbook_book_style_required");
            return null;
        } else if (StringUtils.isBlank(currentMotorBook.getBookUsr())) {
            FacesUtil.addErrorMessage(null, "er_motorbook_book_user_required");
            return null;
        } else if (StringUtils.isBlank(currentMotorBook.getDestination())) {
            FacesUtil.addErrorMessage(null, "er_motorbook_book_destination_required");
            return null;
        } else if (StringUtils.isBlank(currentMotorBook.getWorkRemark())) {
            FacesUtil.addErrorMessage(null, "er_motorbook_book_workremark_required");
            return null;
        }


        try {
            // 添加预约信息
            currentMotorBook.setBookTime(new Date());
            motorInfoMgr.addBookInfo(currentMotorBook);
            currentMotorInfo.getWlbMotorBooks().add(currentMotorBook);
            motorBooks.setWrappedData(currentMotorInfo.getWlbMotorBooks());
        } catch (MotorBookExistsException ex) {
            FacesUtil.addErrorMessage(null, "er_motorbook_book_exists", currentMotorInfo.getMotorNum());
            return null;
        }
        
        // 若使用人的邮箱存在，发邮件给使用人
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String bookStyle = null;
            if (currentMotorBook.getBookStyle() == WlbMotorBook.BOOK_STYLE_MORNING) {
                bookStyle = FacesUtil.getString("table_column_motor_morning");
            } else {
                bookStyle = FacesUtil.getString("table_column_motor_afternoon");
            }
        
        try {
            ItscUserInfo bookUser = userService.findUserByChName(currentMotorBook.getBookUsr());
            if (bookUser != null && StringUtils.isNotEmpty(bookUser.getUserMail())) {
                ItscMailMessage mailMessage = new ItscMailMessage();
                List<String> receivers = new ArrayList<String>();
                receivers.add(bookUser.getUserMail());
                mailMessage.setMailReceivers(receivers);
                mailMessage.setMailFrom(FacesUtil.getString("info_mail_motor_book_from"));
                //mailMessage.setMailFrom("13857508809@139.com");
                mailMessage.setSubject(FacesUtil.getString("info_mail_motor_book_title",
                        currentMotorInfo.getMotorNum(),
                        currentMotorInfo.getDriverName(),
                        currentMotorInfo.getDriverPhone(),
                        df.format(currentMotorBook.getBookTime()),
                        bookStyle));
                mailService.sendHtmlEmailsByAsyn(mailMessage); // 异步发送邮件
            }
    
        } catch (UserNotExistException ex) {
            logger.warn("can't send email to motor user because user (" 
                    + currentMotorBook.getBookUsr() +") don't exist.");
        }

        FacesUtil.addInfoMessage(null, "info_motorbook_book_success", df.format(searchDate),
                currentMotorBook.getDisplayBookStyle(), currentMotorInfo.getMotorNum());
        return null;
    }

    public String cancelBook() {
        int rowIndex = motorBooks.getRowIndex();
        List<WlbMotorBook> currentMotorBooks = (List<WlbMotorBook>) motorBooks.getWrappedData();
        WlbMotorBook toCancelBook = currentMotorBooks.get(rowIndex);
        motorInfoMgr.removeBookInfo(toCancelBook.getBookId());
        currentMotorBooks.remove(rowIndex);
        motorBooks.setWrappedData(currentMotorInfo.getWlbMotorBooks());
        
        // 若使用人的邮箱存在，发邮件给使用人
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String bookStyle = null;
            if (toCancelBook.getBookStyle() == WlbMotorBook.BOOK_STYLE_MORNING) {
                bookStyle = FacesUtil.getString("table_column_motor_morning");
            } else {
                bookStyle = FacesUtil.getString("table_column_motor_afternoon");
            }
        
        try {
            ItscUserInfo bookUser = userService.findUserByChName(toCancelBook.getBookUsr());
            if (bookUser != null && StringUtils.isNotEmpty(bookUser.getUserMail())) {
                ItscMailMessage mailMessage = new ItscMailMessage();
                List<String> receivers = new ArrayList<String>();
                receivers.add(bookUser.getUserMail());
                mailMessage.setMailReceivers(receivers);
                mailMessage.setMailFrom(FacesUtil.getString("info_mail_motor_book_from"));
                //mailMessage.setMailFrom("13857508809@139.com");
                mailMessage.setSubject(FacesUtil.getString("info_mail_motor_cancel_title",
                        currentMotorInfo.getMotorNum(),
                        currentMotorInfo.getDriverName(),
                        currentMotorInfo.getDriverPhone(),
                        df.format(toCancelBook.getBookTime()),
                        bookStyle));
                mailService.sendHtmlEmailsByAsyn(mailMessage); // 异步发送邮件
            }
    
        } catch (UserNotExistException ex) {
            logger.warn("can't send email to motor user because user (" 
                    + currentMotorBook.getBookUsr() +") don't exist.");
        }
        
        FacesUtil.addInfoMessage(null, "info_motorbook_cancel_success", df.format(searchDate),
                currentMotorBook.getDisplayBookStyle(), currentMotorInfo.getMotorNum());
        return null;
    }

    /**
     * 获取可预订的时间段
     */
    public List<SelectItem> getBookStyleList() {
        HashMap<Integer, String> bookStyleMap = new HashMap();
        bookStyleMap.put(WlbMotorBook.BOOK_STYLE_MORNING, FacesUtil.getString("table_column_motor_morning"));
        bookStyleMap.put(WlbMotorBook.BOOK_STYLE_AFTERNOON, FacesUtil.getString("table_column_motor_afternoon"));
        List<WlbMotorBook> currentMotorBooks = this.currentMotorInfo.getWlbMotorBooks();
        if (currentMotorBooks != null) {
            for (WlbMotorBook motorBook : currentMotorBooks) {
                bookStyleMap.remove(Integer.valueOf(motorBook.getBookStyle()));
            }
        }
        List<SelectItem> bookStyleList = new ArrayList<SelectItem>();
        for (Integer key : bookStyleMap.keySet()) {
            bookStyleList.add(new SelectItem(key.intValue(), bookStyleMap.get(key)));
        }
        return bookStyleList;
    }

    /**
     * 返回上一页
     *
     * @return 上一页
     */
    public String toLastPage() {
        queryData();
        return "motorinfo_book";
    }

    public String outputAllMotorInfo() {
        return null;
    }

    public int getDomainId() {
        return domainId;
    }

    public void setDomainId(int domainId) {
        this.domainId = domainId;
    }

    public int getCurrentOperation() {
        return currentOperation;
    }

    public List<SelectItem> getDomainList() {
        if (this.domainList == null) {
            List<ItscDomainInfo> domainInfos = domainMgr.findAllDomains();
            domainList = new ArrayList<SelectItem>();
            for (ItscDomainInfo domainInfo : domainInfos) {
                domainList.add(new SelectItem(domainInfo.getDomainId(), domainInfo.getDomainName()));
            }
        }
        return domainList;
    }

    public String getDriverName() {
        return driverName;
    }

    public void setDriverName(String driverName) {
        this.driverName = driverName;
    }

    public String getMotorNumber() {
        return motorNumber;
    }

    public void setMotorNumber(String motorNumber) {
        this.motorNumber = motorNumber;
    }

    public void setDomainMgr(IDomainService domainMgr) {
        this.domainMgr = domainMgr;
    }

    public void setMotorInfoMgr(IMotorInfoMgr motorInfoMgr) {
        this.motorInfoMgr = motorInfoMgr;
    }

    public WlbMotorInfo getCurrentMotorInfo() {
        return currentMotorInfo;
    }

    public Date getSearchDate() {
        return searchDate;
    }

    public void setSearchDate(Date searchDate) {
        this.searchDate = searchDate;
    }

    public WlbMotorBook getCurrentMotorBook() {
        return currentMotorBook;
    }

    public void setCurrentMotorBook(WlbMotorBook currentMotorBook) {
        this.currentMotorBook = currentMotorBook;
    }

    public DataModel getMotorBooks() {
        return motorBooks;
    }

    public void setMotorBooks(DataModel motorBooks) {
        this.motorBooks = motorBooks;
    }

    public void setMailService(MailService mailService) {
        this.mailService = mailService;
    }

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }
}
